import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
/*FutureBuilder是一个很实用的组件而且功能强大，在实际的项目中也是用的很多的。
FutureBuilder最常用的场景应该是异步的网络请求，示例的代码如下：*/
class FutureBuilderDemo extends StatefulWidget {


  @override
  State<StatefulWidget> createState() =>FutureBuilderState();
}

class FutureBuilderState extends State<FutureBuilderDemo>{
  late Future<dynamic> data;

  Future<dynamic> fetchData() async{
    await Future.delayed(Duration(seconds: 3));
    return http.get('https://www.baidu.com/');
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FutureBuilder'),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future:fetchData(),
        builder: (BuildContext context, AsyncSnapshot snapshot){
          if(snapshot.connectionState==ConnectionState.done){
            if(snapshot.hasData){
              return Container(
                alignment: Alignment.center,
                child: Text('loaded success'),
              );
            }else{
              return Container(
                alignment: Alignment.center,
                child: Text('loaded error'),
              );
            }
          }else {
            return Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            );
          }

        },
      ),
    );
  }
}
